import * as UserApi from '@/api/member/user.js';
import * as WeixinApi from '@/api/weixin/weixin.js';
import diyJson from '@/config/diy.js';
import {BASE_CONFIG} from "@/config/app";

const app = getApp();
export const mixins = {
  components: {},
  data() {
    return {
      themConfig: diyJson.commonStyle,
      rules: [],
      invite: {},
      tagStyle: {
        img: 'width:100%;display:block;',
        table: 'width:100%',
        video: 'width:100%'
      },
      qrCodePath: '',
      showLoading: true,
      content: ``,
      canvasHeight: 1000,
      bgImageHeight: 700,
      pageBody: {
        pageWidth: app.globalData.windows.pageWidth,
      },
      posterPath: '', // 用来保存生成的海报路径
      bgImage: 'https://minio.thisforyou.cn:1443/school/static/user-poster.png', // 海报背景图片的URL
      qrCode: '' // 二维码图片的URL
    }
  },
  onShow() {
    this.loadingBgInfo();
    this.getInviteCode();
    this.getCommissionRule();
  },
  created() {

  },
  async mounted() {
    uni.showLoading({
      title: '海报生成中',
    });
    let count = 0;
    const maxRetries = 10;
    while (count < maxRetries && !this.qrCode) {
      ++count;
      await this.asyncTask();
    }
    if (this.qrCode) {
      this.generatePoster();
    }else {
      uni.hideLoading();
    }
  },

  onReady() {

  },

  methods: {
    async asyncTask() {
      // 模拟一个异步任务
      return new Promise(resolve => setTimeout(resolve, 500)); // 1秒后完成
    },

    qrR(e) {
      // #ifndef MP
      if (!this.qrCode) {
        this.qrCode = e;
      }
      // #endif
    },

    genMaQrCode(code) {
      WeixinApi.getQrCode(
          {
            appId:BASE_CONFIG.appId,
            path: 'pages/index/index',
            envVersion: BASE_CONFIG.active==='prod'?'release':'develop',
            params: 'userCode=' + code,
          }
      ).then(res => {
        this.qrCode = 'data:image/png;base64,' + res.data;
      })
    },

    loadingBgInfo() {
      uni.getImageInfo({
        src: this.bgImage,
        success: (bgRes) => {
          // 图片缩小比例
          let point = this.pageBody.pageWidth / bgRes.width;
          let imgHeight = this.bgImageHeight = bgRes.height * point;
          // 设置海报高度
          this.$nextTick(() => {
            this.canvasHeight = imgHeight + 130 + 10 + 10;
          });
        }
      });
    },

    generatePoster() {
      if (!this.posterPath) {

        const ctx = uni.createCanvasContext('posterCanvas', this);
        ctx.clearRect(0, 0, this.pageBody.pageWidth, this.canvasHeight);  // 清空画布
        ctx.setFillStyle('#FFFFFF');
        ctx.fillRect(0, 0, this.pageBody.pageWidth, this.canvasHeight);  // 清空画布

        let that = this;

        // 加载背景图并绘制
        uni.getImageInfo({
          src: this.bgImage,
          success: (bgRes) => {

            // 图片缩小比例
            let point = that.pageBody.pageWidth / bgRes.width;
            let imgHeight = bgRes.height * point;

            // 设置海报高度
            that.$nextTick(() => {
              that.canvasHeight = imgHeight + 130 + 10 + 10;
            });

            // 绘制背景图
            ctx.drawImage(bgRes.path, 0, 0, this.pageBody.pageWidth,
                bgRes.height * point);

            // 绘制二维码图
            let qrWidth = 130;

            // console.log("that.qrCode", that.qrCode)

            // 绘制文字
            ctx.setFontSize(15);  // 设置文字大小
            ctx.setFillStyle('#303133');  // 设置文字颜色
            ctx.fillText(this.invite.userName + '邀请您加入', qrWidth + 25,
                imgHeight + 55); // 在二维码右侧绘制文字

            ctx.setFontSize(15);  // 设置文字大小
            ctx.setFillStyle('#303133');  // 设置文字颜色
            ctx.fillText('微信扫一扫或者长按识别二维码', qrWidth + 25,
                imgHeight + 95); // 在二维码右侧绘制文字

            // #ifdef MP
            const fs = uni.getFileSystemManager();
            const base64Data = that.qrCode; // 你的 Base64 数据
            const filePath = `${wx.env.USER_DATA_PATH}/qrCode.png`;
            fs.writeFile({
              filePath: filePath,
              data: base64Data.replace(/^data:image\/\w+;base64,/, ''),
              encoding: 'base64',
              success: (res) => {
                console.log('文件写入成功', res, filePath);
                // 然后可以使用临时文件路径
                ctx.drawImage(filePath, 10, imgHeight + 10, qrWidth,
                    qrWidth);
              },
              fail: (err) => {
                console.error('写入文件失败', err);
              }
            });
            // #endif

            // #ifndef MP
            ctx.drawImage(that.qrCode, 10, imgHeight + 10, qrWidth,
                qrWidth);
            // #endif


            // 确保绘制完成后再进行保存
            setTimeout(() => {
              ctx.draw(false, () => {
                console.log('绘制完成，开始保存');  // 调试输出
                uni.canvasToTempFilePath({
                  canvasId: 'posterCanvas',
                  success: (res) => {
                    console.log('生成海报成功:', res.tempFilePath);  // 调试输出
                    that.posterPath = res.tempFilePath;

                    setTimeout(()=>{
                      uni.hideLoading();
                    },1000)

                    // that.saveToLocal(res.tempFilePath);
                  },
                  fail: (err) => {
                    console.log('生成海报失败', err);
                  }
                });
              }, 500)
            }, 500)
          },
          fail: (err) => {
            console.log('背景图加载失败', err);
          }
        });
      }
      uni.hideLoading();
    },

    async getInviteCode() {
      let res = await UserApi.getInviteCode();

      this.invite = res.data;
      this.invite.shareCode = BASE_CONFIG.H5WebHost + "?shareCode="
          + res.data.code;
      console.log("邀请码内容", this.invite.shareCode)
      console.log("getInviteCode", res);
      // #ifdef MP
      this.genMaQrCode(res.data.code);
      // #endif
    },

    copyShareLink() {
      uni.setClipboardData({
        data: this.invite.shareCode,
        success: function () {
          uni.showToast({
            title: '已复制，去粘贴发送吧～',
            icon: 'success',
            duration: 2000
          });
        }
      });
    },

    getCommissionRule() {
      UserApi.getCommissionRule().then(res => {
        this.rules = res.data;
      })
    },
    // 保存海报到本地
    saveToLocal(filePath) {
      // const link = document.createElement('a');
      // link.href = filePath; // 临时文件路径
      // link.download = 'poster.png'; // 默认下载的文件名
      // // 触发下载
      // link.click();

      // #ifdef MP
      uni.showLoading({
        title: '保存中',
      });
      wx.saveImageToPhotosAlbum({
        filePath: filePath,
        success(res) {
          uni.showToast({
            title: "保存成功"
          })
          uni.hideLoading();
        },
        fail(err) {
          console.error('保存图片失败', err);
          uni.hideLoading();
        }
      });
      // #endif
    },

    tipClick(show) {
      if (show) {
        this.$refs.modal.open();
      } else {
        this.$refs.modal.close();
      }
    },

    btnColor() {
      return 'linear-gradient(to top,' + this.themConfig.theme.subColor + ','
          + this.themConfig.theme.color + ')'
      // return' linear-gradient(to right, rgb(66, 83, 216), rgb(213, 51, 186))';
    },
  }

  // #ifdef MP
  ,onShareAppMessage: function () {
    return {
      title: this.invite.userName+'邀请您加入',
      imageUrl: this.posterPath,
      desc: '',
      path: '/pages/index/index?shareCode='+this.invite.code
    };
  },
  // #endif
}
